package com.koomii.common.util;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.util.Iterator;
import java.util.Map;

/**
 * Describe:HttpClientUtil
 * User:
 * Date: 2010-08-11
 * Time: 09:58:44
 */
public class HttpClientUtil {
	private final static Logger log = LogManager.getLogger(HttpClientUtil.class);
    private final static String CHARSET_GBK = "gbk";
    private final static String CHARSET_UTF="utf-8";
    private final static int defaultTimeout = 30000;

    public static String executeHttpRequestGBK(String url, Map<String, String> keyValueMap) {
        return executeHttpRequest(url,keyValueMap,CHARSET_GBK,defaultTimeout);
    }

    public static String executeHttpRequestUTF(String url, Map<String, String> keyValueMap) {
        return executeHttpRequest(url,keyValueMap,CHARSET_UTF,defaultTimeout);
    }
    /***
     *
     * @param url  请求url
     * @param keyValueMap  提交参数
     * @param charSet  字符编码
     * @param timeout  请求响应时间
     * @return
     */
    public static String executeHttpRequest(String url, Map<String, String> keyValueMap,String charSet,int timeout) {
        HttpClient client = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        try {
            //设置请求参数
            if (keyValueMap != null) {
                Iterator it = keyValueMap.entrySet().iterator();
                NameValuePair[] parameters = new NameValuePair[keyValueMap.size()];
                int c = 0;
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
                    NameValuePair nvp = new NameValuePair();
                    nvp.setName(entry.getKey());
                    nvp.setValue(entry.getValue());
                    parameters[c] = nvp;
                    c++;
                }
                postMethod.addParameters(parameters);
            }
            log.debug("query uri ===============" + postMethod.getURI());
            postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charSet);
            //todo:设置超时时间
            postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, timeout);
            int statusCode = client.executeMethod(postMethod);
            if (statusCode != HttpStatus.SC_OK) {
                log.info("request '" + url + "' failed,the status is not 200,status:" + statusCode);
                return "";
            }
            String responseBody = postMethod.getResponseBodyAsString();
            return responseBody;
        } catch (Exception e) {
            log.error("executeHttpRequestString发生异常！请检查网络和参数url:"+url, e);
        } finally {
            postMethod.releaseConnection();
        }
        return null;
    }
}
